package com.xiaomi.eco.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.google.common.base.Joiner;
import com.xiaomi.eco.dal.entity.*;
import com.xiaomi.eco.mapper.EcoCompanyTaskEntityMapper;
import com.xiaomi.eco.mapper.EcoMethodDimensionEntityMapper;
import com.xiaomi.eco.mapper.EcoServiceDimensionEntityMapper;
import com.xiaomi.eco.service.EcoCompanyWebMappingEntityService;
import com.xiaomi.eco.service.EcoCompanyWhiteListEntityService;
import com.xiaomi.eco.service.FeiShuInterfaceService;
import com.xiaomi.eco.service.TaskValidateService;
import com.xiaomi.eco.utils.EcoServiceQualityAlarm;
import com.xiaomi.eco.utils.RequestUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.time.Instant;
import java.time.LocalDate;
import java.time.ZoneId;
import java.time.ZonedDateTime;
import java.time.temporal.ChronoUnit;
import java.util.*;

import static com.xiaomi.eco.dal.enums.TaskStatusEnum.CONSULT;
import static com.xiaomi.eco.dal.enums.TaskStatusEnum.SUGGESTION;
import static com.xiaomi.eco.utils.EcoServiceQualityAlarm.*;

@Service
@Slf4j
public class TaskValidateServiceImpl implements TaskValidateService {
    @Resource
    EcoCompanyTaskEntityMapper ecoCompanyTaskEntityMapper;

    @Resource
    EcoCompanyWebMappingEntityService ecoCompanyWebMappingEntityService;


    @Resource
    EcoMethodDimensionEntityMapper ecoMethodDimensionEntityMapper;

    @Resource
    FeiShuInterfaceServiceImpl feiShuInterfaceService;

    @Resource
    EcoCompanyTaskListEntityServiceImpl ecoCompanyTaskListEntityService;

    @Autowired
    private EcoCompanyWhiteListEntityService ecoCompanyWhiteListEntityService;


    public void checkInterfaceRequirements() {
        LambdaQueryWrapper<EcoCompanyTaskEntity> queryWrapper=new LambdaQueryWrapper<>();
        queryWrapper.eq(EcoCompanyTaskEntity::getTaskStatus,CONSULT.getName()); //查询是否在优化中
        List<EcoCompanyTaskEntity> ecoCompanyTaskEntityList = ecoCompanyTaskEntityMapper.selectList(queryWrapper);
//        List<EcoCompanyTaskEntity> ecoCompanyTaskEntityList= ecoCompanyTaskEntityMapper.getTaskStatus(); //获取数据库中所以的任务对象
        for (EcoCompanyTaskEntity ecoCompanyTaskEntity : ecoCompanyTaskEntityList) {
            String taskId = ecoCompanyTaskEntity.getTaskId(); //获得taskId（数据库中）
            int id = ecoCompanyTaskEntity.getId();
            if (taskId == null || taskId.isEmpty()) {
                log.error("EcoCompanyTaskEntity is not exit taskId");
                continue;
            }
            String feiShuTaskDetail = feiShuInterfaceService.selectTaskFeiShu(taskId); //从飞书中获得详情
            JSONObject jsonObject = JSONObject.parseObject(feiShuTaskDetail); //将对应数据转换为JSON数据进行进一步处理
            if (jsonObject == null || "done".equals(jsonObject.getJSONObject("data").getJSONObject("task").getString("status"))) { //飞书接口数据被删除或者该任务状态为已完成
                log.info("taskid={},飞书任务已完成或对应的飞书任务被删除", taskId);
                //在数据库中查询,（多条数据的情况，取查询天时间最晚的数据,只取一个值）
                EcoMethodDimensionEntity ecoMethodDimensionEntity = ecoMethodDimensionEntityMapper.getEcoMethodDimensionByHttpMethodName(ecoCompanyTaskEntity.getMethodName(), ecoCompanyTaskEntity.getMethodType());
                if(ecoMethodDimensionEntity==null){
                    log.info("methodName={},taskId={},过去一天被删除或者未被调用",ecoCompanyTaskEntity.getMethodName(),taskId);
                    continue;
                }
                //验证指标状态
                String taskUsabilityStatus = validateUsabilityMetrics(ecoMethodDimensionEntity);
                if (taskUsabilityStatus.isEmpty()) {
                    log.info("taskId={},飞书任务核验指标仍完成", taskId);
                    long compolishTime = Long.parseLong(LocalDate.now().toString().replaceAll("-", ""));
                    ecoCompanyTaskEntityMapper.updateTaskStatusByTaskId(taskId, SUGGESTION.getName(), compolishTime); //修改任务状态为已完成
                    //删除飞书任务
                    feiShuInterfaceService.deleteTaskFeishu(taskId);
                } else {
                    if (jsonObject == null) {
                        long statusTimes = System.currentTimeMillis();
                        String applicationId = ecoMethodDimensionEntity.getApplicationId();
                        String responseComment = insertFeishuTask(ecoCompanyTaskEntity.getMethodName(), applicationId, statusTimes, taskUsabilityStatus,ecoCompanyTaskEntity); //插入已完成的任务
                        String taskIdNew = JSONObject.parseObject(responseComment).getJSONObject("data").getJSONObject("task").getString("guid");
                        String taskUrl = JSONObject.parseObject(responseComment).getJSONObject("data").getJSONObject("task").getString("url");
                        log.info("飞书任务被人为删除，新增飞书任务taskId={}", taskIdNew);
                        ecoCompanyTaskEntityMapper.updateTaskIdById(id, taskIdNew, taskUrl);
                        ecoCompanyTaskEntityMapper.updateTaskTypeByTaskId(taskIdNew, taskUsabilityStatus, ecoMethodDimensionEntity.getTakesTimeP95(), ecoMethodDimensionEntity.getTakesTimeP99(),ecoMethodDimensionEntity.getNumberOfErrors()==null? 0:(int) Double.valueOf(ecoMethodDimensionEntity.getNumberOfErrors()).doubleValue()); //转数据
                    } else {
                        log.info("taskId={},飞书任务核验指标后未完成", taskId);
                        //根据案例修改了模版的时间为0，代表飞书任务为未完成的状态
                        updateFeiShuTask(taskId);
                        //根据接口数据修改数据库中taskType
                        ecoCompanyTaskEntityMapper.updateTaskTypeByTaskId(taskId, taskUsabilityStatus, ecoMethodDimensionEntity.getTakesTimeP95(), ecoMethodDimensionEntity.getTakesTimeP99(), ecoMethodDimensionEntity.getNumberOfErrors()==null? 0:(int) Double.valueOf(ecoMethodDimensionEntity.getNumberOfErrors()).doubleValue());
                    }
                }
            }
        }

    }


//    public void checkSingalStatus(String taskId, String methodName, String methodType) {
//        String feiShuTaskDetail = feiShuInterfaceService.selectTaskFeiShu(taskId); //从飞书中获得详情
//        System.out.println(feiShuTaskDetail);
//        JSONObject jsonObject = JSONObject.parseObject(feiShuTaskDetail); //将对应数据转换为JSON数据进行进一步处理
//        jsonObject = null;
//        if (jsonObject == null || "done".equals(jsonObject.getJSONObject("data").getJSONObject("task").getString("status"))) { //飞书接口数据被删除或者该任务状态为已完成
//            //在数据库中查询并计算可用性指标
//            List<EcoMethodDimensionEntity> ecoMethodDimensionEntityList = ecoMethodDimensionEntityMapper.getEcoMethodDimensionByHttpMethodName(methodName, methodType);
//            //List<EcoServiceDimensionEntity> ecoServiceDimensionEntityList=ecoServiceDimensionEntityMapper.getEcoServiceDimensionByApplicationId("2080","admin-service");
//            String taskUsabilityStatus = validateUsabilityMetrics(ecoMethodDimensionEntityList);
////            String taskUsabilityStatus=Joiner.on("").join(new ArrayList<>()); //走另一条if数据支路
//            if (taskUsabilityStatus.isEmpty()) {
//                ecoCompanyTaskEntityMapper.updateTaskStatusByTaskId(taskId, "已完成"); //修改任务状态为已完成
//                //删除飞书任务
//                feiShuInterfaceService.deleteTaskFeishu(taskId);
//            } else {
//                if (jsonObject == null) {
//                    long statusTimes = System.currentTimeMillis() / 1000;
//                    String applicationId = ecoMethodDimensionEntityList.get(ecoMethodDimensionEntityList.size() - 1).getApplicationId();
//                    String responseComment = insertFeishuTask(methodName, applicationId, statusTimes); //插入已完成的任务，后续修改
//                    String taskIdNew = JSONObject.parseObject(responseComment).getJSONObject("data").getJSONObject("task").getString("guid");
//                    System.out.println(taskIdNew);
//                    ecoCompanyTaskEntityMapper.updateTaskIdById(2697, taskIdNew, responseComment);
//                    ecoCompanyTaskEntityMapper.updateTaskTypeByTaskId(taskIdNew, taskUsabilityStatus);
//                } else {
//                    //根据案例修改了模版的时间为0，代表飞书任务为未完成的状态
//                    updateFeiShuTask(taskId);
//                    //根据接口数据修改数据库中taskType
//                    ecoCompanyTaskEntityMapper.updateTaskTypeByTaskId(taskId, taskUsabilityStatus);
//                }
//
//            }
//        }
//    }

    public Boolean updateFeiShuTask(String taskId) {
//        long completeTime = System.currentTimeMillis();
        String updateTask = "{\n" +
                "    \"task\": {\n" +
                "        \"completed_at\": \"0\"\n" +
                "    },\n" +
                "    \"update_fields\": [\n" +
                "        \"completed_at\"\n" +
                "    ]\n" +
                "}";
        return feiShuInterfaceService.updateTaskFeishu(updateTask, taskId);
    }

    //获取任务截止时间方法-15天后
    public String createEndTime() {
        // 获取当前日期
        LocalDate today = LocalDate.now();
        LocalDate inFifteenDays = null;
        List<EcoCompanyWhiteListEntity> ecoCompanyWhiteListEntityList = ecoCompanyWhiteListEntityService.list();
        for (EcoCompanyWhiteListEntity ecoCompanyWhiteListEntity : ecoCompanyWhiteListEntityList) {
            if (ecoCompanyWhiteListEntity.getCompanyId().isEmpty() && ecoCompanyWhiteListEntity.getCompanyName().isEmpty()
                    && ecoCompanyWhiteListEntity.getHttpMethod().isEmpty()) {
                // 将今天的日期加上15天
                inFifteenDays = today.plus(ecoCompanyWhiteListEntity.getDays(), ChronoUnit.DAYS);
            }
        }

        return inFifteenDays.toString();
    }


    public String insertFeishuTask(String methodName, String applicationId, long stausTimes, String taskUsabilityStatus, EcoCompanyTaskEntity ecoCompanyTaskEntity) {
        //从数据表中拿到ecoCompanyWebMappingEntity字段
        EcoCompanyWebMappingEntity ecoCompanyWebMappingEntity = ecoCompanyWebMappingEntityService.getOne(
                new LambdaQueryWrapper<EcoCompanyWebMappingEntity>().eq(EcoCompanyWebMappingEntity::getPrinciPhone, ecoCompanyTaskEntity.getPrincipalPhone()).eq(
                        EcoCompanyWebMappingEntity::getPrincipalName, ecoCompanyTaskEntity.getPrincipalName()
                ).eq(EcoCompanyWebMappingEntity::getCompanyName, ecoCompanyTaskEntity.getPrincipalCompany()));

        String userId =ecoCompanyTaskListEntityService.getUserId(applicationId, EcoServiceQualityAlarm.APPLICATION);
//        String openId = ecoCompanyTaskListEntityService.getOpenId(applicationId, APPLICATION);
        String uuid = UUID.randomUUID().toString();
        String futureTime = createEndTime();
        // 使用LocalDate.parse将字符串解析为LocalDate对象
        LocalDate localDate = LocalDate.parse(futureTime);

        ZonedDateTime zonedDateTime = localDate.atStartOfDay(ZoneId.systemDefault());

        long futureTimestamp = zonedDateTime.toInstant().toEpochMilli();
        StringBuilder stringBuilder = new StringBuilder();
        if (availabilityIsNotUpToPar.equals(taskUsabilityStatus)) {
            stringBuilder.append(availabilityIsNotCommom);
        } else if (slowInterface.equals(taskUsabilityStatus)) {
            stringBuilder.append(slowDownCommom);
        }
        stringBuilder.append(methodName);
        String summary = stringBuilder.toString();
        String description = "该任务属于: " + ecoCompanyTaskEntity.getTaskType() + "   p95值: " + ecoCompanyTaskEntity.getTaskTimeP95() + "   p99值: " + ecoCompanyTaskEntity.getTaskTimeP99() + "   错误数: " + ecoCompanyTaskEntity.getErrorNum()+ "   机房: " + (ecoCompanyTaskEntity.getServerZone() == null ? "" : ecoCompanyTaskEntity.getServerZone());
//        String requestTask = "{\n" +
//                "    \"summary\": \"" + summary + "\",\n" +
//                "    \"description\": \"" + description + "\",\n" +
//                "    \"due\": {\n" +
//                "        \"timestamp\": \"" + futureTimestamp + "\",\n" +
//                "        \"is_all_day\": true\n" +
//                "    },\n" +
//                "    \"completed_at\": \"0\",\n" +
//                "    \"members\": [\n" +
//                "        {\n" +
//                "            \"id\": \"" + userId + "\",\n" +
//                "            \"type\": \"user\",\n" +
//                "            \"role\": \"assignee\"\n" +
//                "        },\n" +
//                "        {\n" +
//                "            \"id\": \"" + userId + "\",\n" +
//                "            \"type\": \"user\",\n" +
//                "            \"role\": \"follower\"\n" +
//                "        }\n" +
//                "    ],\n" +
//                "    \"client_token\": \"" + uuid + "\",\n" +
//                "    \"start\": {\n" +
//                "        \"timestamp\": \"" + stausTimes + "\",\n" +
//                "        \"is_all_day\": true\n" +
//                "    },\n" +
//                "    \"reminders\": [\n" +
//                "        {\n" +
//                "            \"relative_fire_minute\": 720\n" +
//                "        }\n" +
//                "    ],\n" +
//                "    \"mode\": 1,\n" +
//                "    \"is_milestone\": false\n" +
//                "}";
        String tasklistId=ecoCompanyWebMappingEntity.getTasklistId();
        String sectionId=ecoCompanyWebMappingEntity.getSectionId();
        String requestTask = String.format(EcoServiceQualityAlarm.creqateTaskParam, summary, description, futureTimestamp, userId, userId, tasklistId, sectionId, uuid, String.valueOf(System.currentTimeMillis()));
        String responseComment = feiShuInterfaceService.insertTaskFeishu(requestTask);
        log.info("insert information={}", responseComment);
        return responseComment;

    }

    public String validateUsabilityMetrics(EcoMethodDimensionEntity ecoMethodDimensionEntity) {
        String methodAvailabilityStr = ecoMethodDimensionEntity.getMethodAvailability();
        String takesTimeP99 = ecoMethodDimensionEntity.getTakesTimeP99();
        String takesTimeP95 = ecoMethodDimensionEntity.getTakesTimeP95();
        String numberOfErrors = ecoMethodDimensionEntity.getNumberOfErrors();

        if ((methodAvailabilityStr != null && Double.parseDouble(methodAvailabilityStr.replaceAll("%", "")) < 99.95) || (numberOfErrors != null && Double.parseDouble(ecoMethodDimensionEntity.getNumberOfErrors()) > 50)) {
            //接口可用性不达标
            return availabilityIsNotUpToPar;
        }

        if (numberOfErrors != null && ecoMethodDimensionEntity.getTotalCalls() != null) {
            double availabilityResult = (ecoMethodDimensionEntity.getTotalCalls() - Double.valueOf(ecoMethodDimensionEntity.getNumberOfErrors())) / ecoMethodDimensionEntity.getTotalCalls();
            if (availabilityResult < 0.9995) {
                //接口可用性不达标
                return availabilityIsNotUpToPar;
            }
        }

        if ((takesTimeP95 != null && Double.parseDouble(takesTimeP95) > 500) || (takesTimeP99 != null && Double.parseDouble(takesTimeP99) > 800)) {
            //慢接口
            return slowInterface;
        }
        return "";
    }

}
